package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("sessions")
public class SessionController {
    @Autowired
    private IUserService userService;
    @PostMapping
    public JSONResult login(String email,String password){
        //登录成功返回成功的json,跳转页面
        //否则获取异常信息
        JSONResult result=new JSONResult();
        try {
        User user=userService.login(email,password);
            UserContext.setCurrentUser(user);
            //只是保存到session中,但是前端是没有办法获取数据的,
            // 因为只封装了失败的信息返回,所以我们需要成功后的信息也封装回去
            result.setResult(user);
        }catch (Exception e){
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }
    @DeleteMapping
    public JSONResult logout(){
        //登录成功返回成功的json,跳转页面
        //否则获取异常信息
        JSONResult result=new JSONResult();
        UserContext.getSession().invalidate();
        return result;
    }
}
